import {messages} from "share/common";
/**
 * Created by 13576 on 2017/11/22.
 */
import React from 'react'
import { connect } from 'react-redux'

import { Form, Spin, Timeline, Popover, Button, Collapse, Table, Select, Affix, message, Popconfirm, notification, Icon, Badge, Row, Col, Input, Steps } from 'antd';
const Step = Steps.Step;
const FormItem = Form.Item;
import "styles/budget/budget-journal-re-check/budget-journal-re-check-detail.scss"
import httpFetch from 'share/httpFetch';
import config from 'config';
import menuRoute from 'routes/menuRoute'
import ApproveHistoryWorkFlow from 'containers/budget/budget-journal/approve-history-work-flow'
import budgetJournalService from 'containers/approve/budget-journl-check/budget-journal-check.service'
class BudgetJournalCheckDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      passLoading: false,
      rejectLoading: false,
      spinLoading: false,
      data: [],
      totalAmount: 0,
      params: {},
      HistoryData: [],
      headerAndListData: {},
      pageSize: 10,
      page: 0,
      total: 0,
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
        onSelect: this.onSelectItem,
        onSelectAll: this.onSelectAll
      },
      organization: {},
      fileList: [],
      infoData: {},
      columns: [
        {
          /*公司*/
          title: messages('approve.key1'/*公司*/), key: "companyName", dataIndex: 'companyName', width: '8%',
          render: companyName => (
            <Popover content={companyName}>
              {companyName}
            </Popover>)
        },
        {
          /*部门*/
          title: messages('approve.key2'/*部门*/), key: "departmentName", dataIndex: 'departmentName', width: '8%',
          render: unitName => (
            <Popover content={unitName}>
              {unitName}
            </Popover>)

        },
        {          /*人员*/
          title: messages('approve.key3'/*申请人*/), key: "employeeName", dataIndex: 'employeeName',
          render: recode => (
            <Popover content={recode}>
              {recode}
            </Popover>)
        },
        {
          /*预算项目*/
          title: messages('approve.key4'/*预算项目*/), key: "itemName", dataIndex: 'itemName', width: '16%',
          render: itemName => (
            <Popover content={itemName}>
              {itemName}
            </Popover>)
        },
        {
          /*期间*/
          title: messages('approve.key5'/*期间*/), key: "periodName", dataIndex: 'periodName', width: '6%',

        },
        {
          /*季度*/
          title: messages('approve.key6'/*预算季度*/), width: '6%',
          key: "periodQuarterName",
          dataIndex: 'periodQuarterName'
        },
        {
          /*年度*/
          title: messages('approve.key7'/*预算年度*/), key: "periodYear", dataIndex: 'periodYear', width: '8%'
        },
        {
          /*币种*/
          title: messages('approve.key8'/*币种*/), key: "currency", dataIndex: 'currency', width: '8%'
        },
        {
          /*汇率*/
          title: messages('approve.key9'/*汇率*/), key: "rate", dataIndex: 'rate', width: '8%',
        },
        {
          /*金额*/
          title: messages('approve.key10'/*金额*/), key: "amount", dataIndex: 'amount',
          render: recode => (
            <Popover content={this.filterMoney(recode)}>
              {this.filterMoney(recode)}
            </Popover>)
        },
        {
          /*本币今额*/
          title: messages('approve.key11'/*本币金额*/),
          key: "functionalAmount",
          dataIndex: 'functionalAmount',
          render: recode => (
            <Popover content={this.filterMoney(recode)}>
              {this.filterMoney(recode)}
            </Popover>)
        },
        {
          /*数字*/
          title: messages('approve.key12'/*数量*/), key: "quantity", dataIndex: 'quantity', with: '8%',
        },
        {
          /*备注*/
          title: messages('approve.key13'/*行备注*/), key: "remark", dataIndex: 'remark',
          render: remark => (
            <Popover content={remark}>
              {remark}
            </Popover>)
        },
      ],
      budgetJournalCheckPage: menuRoute.getRouteItem('budget-journal-check', 'key'),    //预算日记账审核
      //审批意见
      approvalTxt: ''
    };
  }

  componentWillMount = () => {
    this.getToleAmount();
    this.getBudgetJournalHead();
    this.getBudgetJournalLine();
  }

  //获取日记账总金额
  getToleAmount() {
    let infoDate = this.state.infoDate;
    budgetJournalService.getTotalCurrencyAmount(this.props.params.journalCode).then((response) => {
      let totalAmount = response.data;
      this.setState({ infoDate, totalAmount });
    })
  }

  //获取日记账头
  getBudgetJournalHead() {
    const budgetCode = this.props.params.journalCode;

    budgetJournalService.getBudgetJournalHeaderDetil(budgetCode).then((request) => {
      this.getDimensionByStructureId(request.data.structureId);
      let headerData = request.data;
      // this.getApproveHistory(headerData);
      headerData.attachmentOID.map((item) => {
        this.getFileByAttachmentOID(item);
      })
      let headerAndListData = {
        dto: request.data,
        list: [],
      }
      this.setState({
        headerData: headerData,
        headerAndListData: headerAndListData,
        infoData: request.data
      }, () => {
        this.getToleAmount();
      })
    })
  }

  //获取日记账行
  getBudgetJournalLine() {
    let params = {};
    params.page = this.state.page;
    params.size = this.state.pageSize;
    this.setState({
      loading: true,
      spinLoading: true,
    })
    const budgetCode = this.props.params.journalCode;
    budgetJournalService.getBudgetJournalLineDetil(budgetCode, params).then((response) => {
      this.setState({
        loading: false,
        spinLoading: false
      })
      let listData = response.data;
      this.setState({
        data: listData,
        total: Number(response.headers['x-total-count']),
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch((e) => {
      this.setState({
        loading: false,
        spinLoading: false
      })
      message.error(e.response.data.message);
    })

  }


  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
        loading: true
      }, () => {
        this.getBudgetJournalLine();
      })
  };


  //根据attachmentOID，查询附件
  getFileByAttachmentOID = (value) => {
    let valueData = {};
    valueData.oid = value;
    budgetJournalService.getFileByAttachmentOID(valueData).then((resp) => {
      let fileList = this.state.fileList;
      fileList.addIfNotExist(resp.data)
      this.setState({
        fileList: fileList
      })
    }).catch(e => {
      message.error(`${messages('approve.key14'/*获取附件失败*/)},${e.response.data.message}`);

    })

  }



  //根据预算表id，获得维度
  getDimensionByStructureId = (value) => {
    httpFetch.get(`${config.budgetUrl}/api/budget/journals/getLayoutsByStructureId?isEnabled=true&structureId=${value}`).then((resp) => {
      this.getColumnsAndDimensionhandleData(resp.data);
    }).catch(e => {
      message.error(`${messages('approve.key15'/*获得维度失败*/)},${e.response.data.message}`);

    })
  }

  //根据预算表的维度.获取维度Columuns
  getColumnsAndDimensionhandleData(dimensionList) {
    let columns = this.state.columns;
    for (let i = 0; i < dimensionList.length; i++) {
      const item = dimensionList[i];
      const priority = item.sequenceNumber;
      columns.push(
        {
          title: `${item.dimensionName}`, key: `dimension${priority}ValueName`, dataIndex: `dimension${priority}ValueName`,
          render: recode => (
            <Popover content={recode}>
              {recode}
            </Popover>)
        }
      )
    }
    this.setState({
      columns,
    })
  }

  //通过
  handlePass = () => {
    let approvalTxt = this.state.approvalTxt;
    const dataValue = {
      "approvalTxt": approvalTxt ? approvalTxt : null,
      "entities":
        [{
          "entityOID": this.state.headerAndListData.dto.documentOid,
          "entityType": this.state.headerAndListData.dto.documentType
        }]
    };
    this.setState({
      spinLoading: true,
    });
    budgetJournalService.passJournalWorkflow(dataValue).then((request) => {
      message.success(messages('common.operate.success'));
      let path = this.state.budgetJournalCheckPage.url;
      this.setState({
        spinLoading: false,
      });
      this.context.router.push(path);
    }).catch((e) => {
      message.error(`${messages('common.operate.filed')},${e.response.data.message}`);
      this.setState({
        spinLoading: false,
      })
    })
  }


  //驳回
  handleReject = () => {
    let approvalTxt = this.state.approvalTxt;
    if (approvalTxt) {
      const dataValue = {
        "approvalTxt": approvalTxt ? approvalTxt : null,
        "entities": [
          {
            "entityOID": this.state.headerAndListData.dto.documentOid,
            "entityType": this.state.headerAndListData.dto.documentType
          }]
      }
      this.setState({
        spinLoading: true,
      })
      httpFetch.post(`${config.baseUrl}/api/approvals/reject`, dataValue).then((request) => {
        message.success(messages('common.operate.success'));
        let path = this.state.budgetJournalCheckPage.url;
        this.context.router.push(path);
        this.setState({
          spinLoading: false,
        })

      }).catch((e) => {
        message.error(`${messages('common.operate.filed')},${e.response.data.message}`);
        this.setState({
          spinLoading: false,
        })
      })
    } else {
      message.error("请输入审批意见");
    }
  }

  //返回列表页
  HandleReturn = () => {
    // let path = this.state.budgetJournalCheckPage.url;
    // this.context.router.push(path);
    menuRoute.goBack(this)
  }

  //返回状态
  getStatus = () => {
    const infoData = this.state.infoData;
    switch (infoData.status) {
      case 'NEW':{ return <Badge status="processing" text={infoData.statusName} />}
      case 'SUBMIT':{ return   <Badge status="warning" text={infoData.statusName}/>}
      case 'SUBMIT_RETURN':{return   <Badge status="warning" text={infoData.statusName}/>}
      case 'REJECT':{ return  <Badge status="error" text={infoData.statusName} />}
      case 'CHECKED':{return < Badge status="default" text={infoData.statusName}/>}
      case 'CHECKING':{return <Badge  status="default"text={infoData.statusName}/>}
      case 'POSTED':{return <Badge status="default" text={infoData.statusName}/>}
      case 'BACKLASH_SUBMIT':{return <Badge status="default"  text={infoData.statusName}/>}
      case 'BACKLASH_CHECKED':{return <Badge status="default"  text={infoData.statusName}/>}
      default: { return <Badge status="default" text={infoData.statusName} /> }
    }
  }

  //获得总金额
  getAmount = () => {
    const data = this.state.totalAmount;
    return data;
  }


  //获取附件
  getFile = () => {
    const fileList = this.state.fileList;
    let file_arr = [];
    fileList.map((link) => {
      file_arr.push(<div key={link.fileURL}><a href={link.fileURL} target="_blank"><Icon type="paper-clip" /> {link.fileName}</a> </div>)
    })
    return file_arr.length > 0 ? file_arr : '-';

  }
  /**
      * 审批意见change事件
      */
  onApprovalTxtChange = (e) => {
    e.preventDefault();
    this.setState({
      approvalTxt: e.target.value
    })
  }

  render() {
    const { data, columns, infoData, headerData, approvalTxt } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="budget-journal-re-check-detail">
        <Spin spinning={this.state.spinLoading}>
          <div className="base-info">
            <div className="base-info-header">
              {messages('approve.key16'/*基本信息*/)}
            </div>

            <Row className="base-info-cent" type="flex" gutter={10}>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key17'/*状态*/)}:</div>
                <div className="beep-info-text">
                  {this.getStatus()}
                </div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key18'/*预算日记账编号*/)}:</div>
                <div className="beep-info-text">{infoData.journalCode ? infoData.journalCode : '-'}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key10'/*金额*/)}:</div>
                <div className="beep-info-text">
                  {this.getAmount()}
                </div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key3'/*申请人*/)}:</div>
                <div className="beep-info-text">{infoData.employeeName ? infoData.employeeName : '-'}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key2'/*部门*/)}:</div>
                <div className="beep-info-text">{infoData.unitName ? infoData.unitName : '-'}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key19'/*创建时间*/)}:</div>
                <div className="beep-info-text">{String(infoData.createdDate).substring(0, 10)}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key20'/*预算日记账类型*/)}:</div>
                <div className="beep-info-text">{infoData.journalTypeName}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key21'/*预算表*/)}:</div>
                <div className="beep-info-text">{infoData.structureName}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key22'/*场景*/)}:</div>
                <div className="beep-info-text">{infoData.scenario}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key23'/*版本*/)}:</div>
                <div className="beep-info-text">{infoData.versionName}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key24'/*编制期段*/)}:</div>
                <div className="beep-info-text">{infoData.periodStrategyName}</div>
              </Col>
              <Col span={8}>
                <div className="base-info-title">{messages('approve.key25'/*附件*/)}:</div>
                <div className="beep-info-text">{this.getFile()}</div>
              </Col>
            </Row>
          </div>

          <Table columns={columns}
            dataSource={data}
            bordered
            size="middle"
            scroll={{ x: '150%' }}
          />
          {infoData.formOid &&
            <div className="collapse">
              <ApproveHistoryWorkFlow data={infoData} infoData={[]} loading={false} />
            </div>
          }
          {this.state.infoData.status === "CHECKED" ?
            (
              <Affix offsetBottom={0} className="bottom-bar">
                <Button className="button-return" style={{ marginLeft: '20px', marginRight: '8px' }} onClick={this.HandleReturn}>{messages('approve.key26'/*返回*/)}</Button>
              </Affix>
            )
            :
            (
              <Affix offsetBottom={0} className="bottom-bar">
                <div>
                  <Row gutter={12} type='flex' justify='start'>
                    <Col offset={1}><span>{messages('approve.key27'/*审批意见*/)}：&nbsp;</span></Col>
                    <Col span={11} >
                      <Input required='true' value={approvalTxt} onChange={this.onApprovalTxtChange} placeholder={messages('common.please.enter')} />
                    </Col>
                    <Col span={1.5} ><Button type="primary" onClick={this.handlePass} loading={this.state.passLoading}>{messages('approve.key28'/*通过*/)}</Button></Col>
                    <Col span={1.5} ><Button type="danger" style={{ background: 'red', color: 'white' }} loading={this.state.rejectLoading} onClick={this.handleReject}>{messages('approve.key29'/*驳回*/)}</Button></Col>
                    <Col span={2} offset={2} ><Button onClick={this.HandleReturn}>{messages('approve.key26'/*返回*/)}</Button></Col>
                  </Row>
                </div>
              </Affix>
            )}
        </Spin>
      </div>

    )
  }

}


BudgetJournalCheckDetail.contextTypes = {
  router: React.PropTypes.object
};


const WebBudgetJournalCheckDetail = Form.create()(BudgetJournalCheckDetail);

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    organization: state.login.organization

  }

}

export default connect(mapStateToProps)(WebBudgetJournalCheckDetail);
